package com.zdya.combatdocuments.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zdya.combatdocuments.component.CombatDocumentConfig;
import com.zdya.combatdocuments.entity.*;
import com.zdya.combatdocuments.entity.vo.ResultVo;
import com.zdya.combatdocuments.ethereum.EthChain;
import com.zdya.combatdocuments.mapper.*;
import com.zdya.combatdocuments.p2pNetwork.NodeUtil;
import com.zdya.combatdocuments.p2pNetwork.P2pClient;
import com.zdya.combatdocuments.p2pNetwork.P2pService;
import com.zdya.combatdocuments.service.NetworkService;
import com.zdya.combatdocuments.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
public class NetworkServiceImpl extends ServiceImpl<NetworkMapper, Network> implements NetworkService {

    private static DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

    @Autowired
    private NetworkMapper networkMapper;
    @Autowired
    private NetworkUserMapper networkUserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    P2pService p2pService;
    @Autowired
    P2pClient p2pClient;
    @Autowired
    NodeUtil nodeUtil;
    @Autowired
    GradeMapper gradeMapper;
    @Autowired
    DocApprovalLimitMapper docApprovalLimitMapper;
    @Autowired
    ChainDataMapper chainDataMapper;


    @Override
    public ResultVo createNet(String name, Long userId, String gradeName, Long gradeTime, Long firstLimittime, Long secondLimittime, Long thirdLimittime) {
        //判断存在同一用户创建的网络名
        String username = userMapper.selectById(userId).getUsername();
        Network network = networkMapper.selectOne(new QueryWrapper<Network>().eq("name", name).eq("create_Name", username));
        if (network == null) {
            /**插入网络表*/
            User user = userMapper.selectById(userId);
            network = new Network();
            network.setName(name);
            network.setCreateDate(System.currentTimeMillis());
            network.setCreateName(user.getUsername());
            String txt = FileUtil.ReadTxt(user.getUsername());
            JSONObject jsonObject = JSONUtil.parseObj(txt);
            String mac = jsonObject.getStr("authorMac");
            network.setAuthorMac(mac);
            String chainid = System.currentTimeMillis() / 1000 + "";
            network.setChainId(chainid);


            try {
                AjaxResult ajaxResult = EthChain.creatChainAndStart(chainid, name, network.getCreateName());
                String code = ajaxResult.getCode();
                if (!"0".equals(code)) {
                    String message = ajaxResult.getMessage();
                    network.setChainId(chainid);
                    network.setContract(message);//合约地址
                } else {
                    KillPortUtils.start();
                    String path = CombatDocumentConfig.getProfile() + File.separator + "ethereum" + File.separator+ network.getName() + "_" + network.getCreateName();
                    cn.hutool.core.io.FileUtil.del(path);
//                    return ResultVoUtil.error("网络创建失败,区块链创建失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
                network.setStatus(1);//合约地址
                networkMapper.updateById(network);
                KillPortUtils.start();
                String path = CombatDocumentConfig.getProfile() + File.separator + "ethereum" + File.separator+ network.getName() + "_" + network.getCreateName();
                cn.hutool.core.io.FileUtil.del(path);
//                return ResultVoUtil.error("网络创建失败,区块链创建失败");
            }



            networkMapper.insert(network);
            /**插入阶段表*/
            Grade grade = new Grade();
            grade.setNetworkId(network.getId());
            if (gradeName == null) {
                gradeName = "第一阶段";
            }
            grade.setGradeName(gradeName);
            if (gradeTime == null) {
                gradeTime = DateUtil.nextWeek().getTime();
            }
            grade.setGradeTime(gradeTime);
            grade.setCreateUser(userId);
            grade.setCreateDate(System.currentTimeMillis());
            gradeMapper.insert(grade);
            /**插入时间限制表*/
            DocApprovalLimit docApprovalLimit = new DocApprovalLimit();
            docApprovalLimit.setNetworkId(network.getId());
            if (firstLimittime == null) {
                firstLimittime = 6l;
            }
            if (secondLimittime == null) {
                secondLimittime = 4l;
            }
            if (thirdLimittime == null) {
                thirdLimittime = 2l;
            }
            docApprovalLimit.setFirstLimittime(firstLimittime);
            docApprovalLimit.setSecondLimittime(secondLimittime);
            docApprovalLimit.setThirdLimittime(thirdLimittime);
            docApprovalLimit.setCreateDate(System.currentTimeMillis());
            docApprovalLimit.setCreateUser(userId);
            docApprovalLimit.setUpdateTime(null);
            docApprovalLimitMapper.insert(docApprovalLimit);
            cerateStarNet(name, user.getUsername(), userId);
            return ResultVoUtil.success("网络启动成功");
        } else {
            return ResultVoUtil.error("创建失败,网络已存在");
        }

    }

    public ResultVo cerateStarNet(String netName, String createName, Long userId) {
        //判断是否存在用户创建的网络，不存在则非初始用户。
        Network network = networkMapper.selectOne(new QueryWrapper<Network>().eq("name", netName).eq("create_name", createName));
        if (network == null) {
            return ResultVoUtil.error("初次启动网络须使用创始用户");
        } else {
            network.setPrimaryName(userMapper.selectById(userId).getUsername());
            networkMapper.updateById(network);
            NetworkUser networkUser = networkUserMapper.selectOne(new QueryWrapper<NetworkUser>()
                    .eq("network_id", network.getId())
                    .eq("user_id", userId));
            if (networkUser != null) {
                networkUser.setStatus(0);
                networkUserMapper.updateById(networkUser);
            } else {
                NetworkUser networkUser1 = new NetworkUser();
                networkUser1.setNetworkId(network.getId());
                networkUser1.setUserId(userId);
                networkUser1.setStatus(0);
                networkUserMapper.insert(networkUser1);
            }
            LambdaQueryWrapper<ChainData> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ChainData::getNetworkId, network.getId());
            List<ChainData> chainDataList = chainDataMapper.selectList(wrapper);
            nodeUtil.setChainDataList(chainDataList);
            /**将此次network做临时缓存*/
            nodeUtil.setLocalNetwork(network);
            nodeUtil.setPrimaryIp(nodeUtil.getLocalIp());
            nodeUtil.setNetworkId(network.getId());
            /**----------------启动时设置当前阶段------------*/
            nodeUtil.setupGrade();
            p2pService.initServer(nodeUtil.getPort());
            nodeUtil.setLocalUser(updateLocalUserIp(userId));
            nodeUtil.updateChainDataTime(System.currentTimeMillis());
            nodeUtil.setSyncDataTime(nodeUtil.getChainDataTime()-1);
            /**定时前端推送节点信息，并监控阶段变化*/
            nodeUtil.threadPool.submit(() -> {
                while (true) {
                    try {
                        Thread.sleep(5000);
                        getUpdateInfo();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            /**定时向丛节点推送上链数据。*/
            nodeUtil.threadPool.submit(() -> {
                while (true) {
                    try {
                        Thread.sleep(10000);
                        syncChainInfo();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            return ResultVoUtil.success("网络启动成功");
        }
    }

    @Override
    public ResultVo starNet(String netName, String createName) {
        Long userId = nodeUtil.getLocalUser().getId();
        //判断是否存在用户创建的网络，不存在则非初始用户。
        Network network = networkMapper.selectOne(new QueryWrapper<Network>().eq("name", netName).eq("create_name", createName));
        if (network == null) {
            return ResultVoUtil.error("启动失败");
        } else {
            network.setPrimaryName(userMapper.selectById(userId).getUsername());
            networkMapper.updateById(network);

            NetworkUser networkUser = networkUserMapper.selectOne(new QueryWrapper<NetworkUser>()
                    .eq("network_id", network.getId())
                    .eq("user_id", userId));
            if (networkUser != null) {
                networkUser.setStatus(0);
                networkUserMapper.updateById(networkUser);
            } else {
                NetworkUser networkUser1 = new NetworkUser();
                networkUser1.setNetworkId(network.getId());
                networkUser1.setUserId(userId);
                networkUser1.setStatus(0);
                networkUserMapper.insert(networkUser1);
            }
            LambdaQueryWrapper<ChainData> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ChainData::getNetworkId, network.getId());
            List<ChainData> chainDataList = chainDataMapper.selectList(wrapper);
            nodeUtil.setChainDataList(chainDataList);
            /**将此次network做临时缓存*/
            nodeUtil.setLocalNetwork(network);
            nodeUtil.setPrimaryIp(nodeUtil.getLocalIp());
            nodeUtil.setNetworkId(network.getId());
            /**----------------启动时设置当前阶段------------*/
            nodeUtil.setupGrade();
            p2pService.initServer(nodeUtil.getPort());
            nodeUtil.setLocalUser(updateLocalUserIp(userId));
            nodeUtil.updateChainDataTime(System.currentTimeMillis());
            nodeUtil.setSyncDataTime(nodeUtil.getChainDataTime()-1);
            //区块链启动
            AjaxResult ajaxResult =null;
            String path = CombatDocumentConfig.getProfile() + File.separator + "ethereum" + File.separator+ network.getName() + "_" + network.getCreateName();
            try {
                KillPortUtils.start();
//                AjaxResult ajaxResult = EthChain.startChain(network.getName(), network.getChainId(), network.getCreateName());

                if(cn.hutool.core.io.FileUtil.exist(path)){
                    ajaxResult = EthChain.startChain(network.getName(), network.getChainId(), network.getCreateName());
                }else{
                    ajaxResult = EthChain.creatChainAndStart(network.getChainId(), network.getName(), network.getCreateName());
                }
                String code = ajaxResult.getCode();
                if ("0".equals(code)) {
//                    networkMapper.delete(new QueryWrapper<Network>().ne("id", 0));
//                    String path = CombatDocumentConfig.getProfile() + File.separator + "ethereum" + File.separator+ network.getName() + "_" + network.getCreateName();
                    cn.hutool.core.io.FileUtil.del(path);
//                    return ResultVoUtil.error("网络启动失败，区块链启动失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
                KillPortUtils.start();
//                String path = CombatDocumentConfig.getProfile() + File.separator + "ethereum" + File.separator+ network.getName() + "_" + network.getCreateName();
                cn.hutool.core.io.FileUtil.del(path);
//                networkMapper.delete(new QueryWrapper<Network>().ne("id", 0));
//                return ResultVoUtil.error("网络启动失败，区块链启动失败");
            }
            /**定时前端推送节点信息，并监控阶段变化*/
            nodeUtil.threadPool.submit(() -> {
                while (true) {
                    try {
                        Thread.sleep(5000);
                        getUpdateInfo();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            /**定时向丛节点推送上链数据。*/
            nodeUtil.threadPool.submit(() -> {
                while (true) {
                    try {
                        Thread.sleep(10000);
                        syncChainInfo();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            return ResultVoUtil.success("网络启动成功");
        }
    }

    /**
     * 如果netUser能查到，则修改状态，查不到则去授权表初次验证
     *
     * @param ipAddress
     * @param userId
     */

    @Override
    public ResultVo joinNet(String ipAddress, Long userId) {
        Network getByPostNet = null;
        User userByid = userMapper.selectById(userId);
        String address = userByid.getAddress();
        String enode ="";
        try {
            //获取到主节点当前网络
            String url = ipAddress + ":"+nodeUtil.getServerPort() + "/documents/network/getByPostNet?address=" + address;
            String s = HttpUtil.get(url);
            getByPostNet = JSONUtil.toBean(s, Network.class);
            enode = getByPostNet.getEnode();
            if(enode==null||"".equals(enode)){
                enode = "123@";
            }
        }catch (Exception e){
            return ResultVoUtil.error("主节点未启动，连接失败");
        }
        int loc = enode.indexOf("@");
        String newStr = enode.substring(0, loc);
        String enodeAddress = newStr + "@" + ipAddress + ":30303?discport=0";
        String txt = FileUtil.ReadTxt(userByid.getUsername());
        JSONObject jsonObject = JSONUtil.parseObj(txt);
        String mac = jsonObject.getStr("authorMac");
        Long expirationTime = jsonObject.getLong("expirationTime");
        if (expirationTime < getByPostNet.getSystemCurrentTime()) {
            return ResultVoUtil.error("连接失败，授权过期");
        }

        //验证通过
        if ((mac).equals(getByPostNet.getAuthorMac()) || getByPostNet.getAuthorMac() == mac) {
            Network network = networkMapper.selectOne(new QueryWrapper<Network>().eq("name", getByPostNet.getName()).eq("create_name", getByPostNet.getCreateName()));
            if (network == null) {
                String chainid = (getByPostNet.getChainId());
                try {
                    AjaxResult ajaxResult = EthChain.creatChainAndStart1(chainid, getByPostNet.getName(), getByPostNet.getCreateName());
                    String code = ajaxResult.getCode();
                    if ("0".equals(code)) {
                        KillPortUtils.start();
                        String path = CombatDocumentConfig.getProfile() + File.separator + "ethereum" + File.separator+ getByPostNet.getName() + "_" + getByPostNet.getCreateName();
                        cn.hutool.core.io.FileUtil.del(path);
//                        return ResultVoUtil.error("网络创建失败,区块链创建失败");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    KillPortUtils.start();
                    String path = CombatDocumentConfig.getProfile() + File.separator + "ethereum" + File.separator+ getByPostNet.getName() + "_" + getByPostNet.getCreateName();
                    cn.hutool.core.io.FileUtil.del(path);
//                    return ResultVoUtil.error("网络创建失败,区块链创建失败");
                }
                boolean b = EthRPCUtil.addPeer("127.0.0.1", enodeAddress);
                if (!b) {
                    String path = CombatDocumentConfig.getProfile() + File.separator + "ethereum" + File.separator+ getByPostNet.getName() + "_" + getByPostNet.getCreateName();
                    cn.hutool.core.io.FileUtil.del(path);
//                    return ResultVoUtil.error("加入网络失败,区块链同步数据失败");
                }
                getByPostNet.setId(null);
                networkMapper.insert(getByPostNet);
                nodeUtil.setLocalNetwork(getByPostNet);
                Long id = getByPostNet.getId();
                nodeUtil.setNetworkId(id);
                NetworkUser networkUser = new NetworkUser();
                networkUser.setNetworkId(id);
                networkUser.setUserId(userId);
                networkUser.setStatus(0);
                networkUserMapper.insert(networkUser);
            } else {
                nodeUtil.setNetworkId(network.getId());
                network.setPrimaryName(getByPostNet.getPrimaryName());
                networkMapper.updateById(network);
                nodeUtil.setLocalNetwork(network);
                //修改netUser表状态
                NetworkUser networkUser = networkUserMapper.selectOne(new QueryWrapper<NetworkUser>().eq("network_id", network.getId()).eq("user_id", userId));
                networkUser.setStatus(0);
                networkUserMapper.updateById(networkUser);
                String chainid = network.getChainId();

                String path = CombatDocumentConfig.getProfile() + File.separator + "ethereum" + File.separator+ getByPostNet.getName() + "_" + getByPostNet.getCreateName();
                AjaxResult ajaxResult = null;
                try {
                    //判断链文件是否存在
                    if(cn.hutool.core.io.FileUtil.exist(path)){
                        ajaxResult = EthChain.startChain1(getByPostNet.getName(), chainid, getByPostNet.getCreateName());
                    }else{
                        ajaxResult = EthChain.creatChainAndStart1(chainid, getByPostNet.getName(), getByPostNet.getCreateName());
                    }

                    String code = ajaxResult.getCode();
                    if ("0".equals(code)) {
                        KillPortUtils.start();
//                        String path = CombatDocumentConfig.getProfile() + File.separator + "ethereum" + File.separator+ getByPostNet.getName() + "_" + getByPostNet.getCreateName();
                        cn.hutool.core.io.FileUtil.del(path);
//                        return ResultVoUtil.error("网络启动失败,区块链启动失败");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    KillPortUtils.start();
//                    String path = CombatDocumentConfig.getProfile() + File.separator + "ethereum" + File.separator+ getByPostNet.getName() + "_" + getByPostNet.getCreateName();
                    cn.hutool.core.io.FileUtil.del(path);
//                    return ResultVoUtil.error("网络启动失败,区块链启动失败");
                }
                boolean b = EthRPCUtil.addPeer("127.0.0.1", enodeAddress);
                if (!b) {
                    KillPortUtils.start();
//                    String path = CombatDocumentConfig.getProfile() + File.separator + "ethereum" + File.separator+ getByPostNet.getName() + "_" + getByPostNet.getCreateName();
                    cn.hutool.core.io.FileUtil.del(path);
//                    return ResultVoUtil.error("加入网络失败,区块链同步数据失败");
                }
            }
            List<User> userList = getByPostNet.getUserList();
            for(User user:userList){
                if(!userByid.getUsername().equals(user.getUsername())) {
                    User userByName = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, user.getUsername()));
                    if (userByName == null) {
                        user.setId(null);
                        userMapper.insert(user);
                        NetworkUser networkUser1 = new NetworkUser();
                        networkUser1.setNetworkId(nodeUtil.getNetworkId());
                        networkUser1.setUserId(user.getId());
                        networkUser1.setStatus(0);
                        networkUserMapper.insert(networkUser1);
                    } else {
                        user.setId(userByName.getId());
                        user.setAvatarUrl(userByName.getAvatarUrl());
                        userMapper.updateById(user);
                        NetworkUser networkUser = networkUserMapper.selectOne(new QueryWrapper<NetworkUser>().eq("network_id", nodeUtil.getNetworkId()).eq("user_id", user.getId()));
                        if (networkUser == null) {
                            NetworkUser networkUser1 = new NetworkUser();
                            networkUser1.setNetworkId(nodeUtil.getNetworkId());
                            networkUser1.setUserId(user.getId());
                            networkUser1.setStatus(0);
                            networkUserMapper.insert(networkUser1);
                        }
                    }
                }
            }

            nodeUtil.setPrimaryIp(ipAddress);
            p2pService.initServer(nodeUtil.getPort());
            nodeUtil.setLocalUser(updateLocalUserIp(userId));
            p2pClient.connectPeer("ws://" + ipAddress + ':' + nodeUtil.getPort());
            log.info("*****节点" + ipAddress + "连接成功");
            /**定时前端推送节点信息，并监控阶段变化*/
            nodeUtil.threadPool.submit(() -> {
                while (true) {
                    try {
                        Thread.sleep(5000);
                        getUpdateInfo();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            return ResultVoUtil.success("连接成功");
        } else {
            return ResultVoUtil.error("连接失败，授权mac不同");
        }
    }

    @Override
    public List<Network> getNetList(Long userId) {
        User user = userMapper.selectById(userId);
        String txt = FileUtil.ReadTxt(user.getUsername());
        JSONObject jsonObject = JSONUtil.parseObj(txt);
        String authorMac = jsonObject.getStr("authorMac");

        User localUser = nodeUtil.getLocalUser();
        String username = localUser.getUsername();
        LambdaQueryWrapper<Network> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Network::getCreateName, username);
        wrapper.eq(Network::getAuthorMac,authorMac);
        List<Network> networks = networkMapper.selectList(wrapper);
        List<Network> collect = networks.stream().sorted(Comparator.comparing(Network::getCreateDate)).collect(Collectors.toList());
        return collect;

    }

    @Override
    public String changeUser(User user) {
        /**将id、ip、ws绑定*///存备份临时list
        nodeUtil.getIp_keyList().add(user);
        String str = JSONUtil.toJsonStr(nodeUtil.getLocalUser());
        User localUser = JSONUtil.toBean(str, User.class);
        localUser.setId(null);
        localUser.setKeystore(null);
        localUser.setPrivateKey(null);
        return JSONUtil.toJsonStr(localUser);
    }

    /**
     * 获取区块高度
     */
    private void getUpdateInfo() {
        if (Objects.nonNull(nodeUtil.client)) {
            try{
                nodeUtil.blockHeight = EthChain.getBlockNumber();
            }catch (Exception e){
            }
            try{
                if (nodeUtil.getLocalIp() == nodeUtil.getPrimaryIp() || (nodeUtil.getLocalIp()).equals(nodeUtil.getPrimaryIp())) {
                    gradeTimeOut();
                }
            }catch (Exception e){
            }
            try{
                JSONObject jsonObject = new JSONObject();
                JSONObject content = new JSONObject();
                content.put("blockHeight", nodeUtil.blockHeight);
                content.put("userNum", nodeUtil.getUserList().size() + 1);
                content.put("primaryIp", nodeUtil.getPrimaryIp());
                content.put("netCreateDate", nodeUtil.getLocalNetwork().getCreateDate());
                content.put("stage", nodeUtil.getGrade());
                content.put("stageList", nodeUtil.getGradeList());
                content.put("stageIndex", nodeUtil.getGradeIndex());
                jsonObject.put("type", 10);
                jsonObject.put("content", content);
                nodeUtil.write(nodeUtil.client, jsonObject.toString());
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 阶段过期判断
     */
    private void gradeTimeOut() {
        //todo:已然要设置grade，gradeList并广播,且判断逻辑修改，
        Grade localGrade = nodeUtil.getGrade();
        int gradeIndex = nodeUtil.getGradeIndex();
        int gradeSize = nodeUtil.getGradeList().size();
        if (System.currentTimeMillis() > localGrade.getGradeTime()) {
            if(gradeIndex < gradeSize-1){
                LambdaQueryWrapper<Grade> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Grade::getNetworkId, nodeUtil.getNetworkId()).orderByAsc(Grade::getCreateDate);
                List<Grade> gradeList = gradeMapper.selectList(wrapper);
                Grade changeGrade = gradeList.get(gradeIndex + 1);
                /**修改内存标志*/
                nodeUtil.setGrade(changeGrade);
                nodeUtil.setGradeIndex(gradeIndex+1);
                /**转发*/
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("type", 9);
                jsonObject.put("grade", changeGrade);
                nodeUtil.updateTableInfo(jsonObject.toString());
            }
        }
    }

    /**
     * 同步上链缓存信息
     */
    private void syncChainInfo() {
        try{
            if(nodeUtil.getSyncDataTime() == nodeUtil.getChainDataTime()){
                return ;
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", 14);
            jsonObject.put("chainDataList", nodeUtil.getChainDataList());
            nodeUtil.setSyncDataTime(nodeUtil.getChainDataTime());
            if (CollectionUtils.isEmpty(nodeUtil.getNodeList())) {
                return;
            }
            log.info("======同步上链信息开始：");
            for(Node node : nodeUtil.getNodeList()){
                String ip = node.getIp();
                if(!(ip).equals("127.0.0.1") || ip != "127.0.0.1" || !(ip).equals(nodeUtil.getPrimaryIp()) || ip != nodeUtil.getPrimaryIp()){
                    nodeUtil.write(node.getWebSocket(), jsonObject.toString());
                }
            }
            log.info("======同步上链信息结束");
        }catch (Exception e){
        }
    }

    /**
     * 更新本地用户表内ip
     *
     * @param userId
     * @return
     */
    private User updateLocalUserIp(Long userId) {
        User user = userMapper.selectById(userId);
        String localIp = nodeUtil.getLocalIp();
        if ((localIp).equals(user.getIp())) {
            return user;
        } else {
            user.setIp(localIp);
            userMapper.updateById(user);
            return user;
        }
    }


}
